import axios from 'axios'

// 创建axios实例
// 直接使用系统环境变量或Vite环境变量
const apiClient = axios.create({
  baseURL: process.env.API_BASE_URL || import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 添加请求拦截器来调试
apiClient.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    console.log('API Request:', config.method?.toUpperCase(), config.baseURL, config.url, config.data)
    const token = localStorage.getItem('accessToken')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    // 对请求错误做些什么
    console.error('API Request Error:', error)
    return Promise.reject(error)
  }
)

// 添加响应拦截器来调试
apiClient.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    console.log('API Response:', response.status, response.data)
    return response
  },
  (error) => {
    // 对响应错误做点什么
    console.error('API Response Error:', error.response?.status, error.response?.data || error.message)
    if (error.response?.status === 401) {
      // 处理未授权错误
      localStorage.removeItem('accessToken')
      window.location.href = '/sign-in'
    }
    return Promise.reject(error)
  }
)

// 登录接口
export interface LoginRequest {
  email: string
  password: string
}

export interface LoginResponse {
  accessToken: string
  user: {
    id: string
    accountNo: string
    email: string
    role: string[]
  }
}

export const login = async (data: LoginRequest): Promise<LoginResponse> => {
  try {
    console.log('Attempting login with:', data)
    console.log('API Base URL:', apiClient.defaults.baseURL)
    const response = await apiClient.post<LoginResponse>('/auth/login', data)
    console.log('Login response:', response.data)
    return response.data
  } catch (error: any) {
    console.error('Login error:', error.response?.data || error.message)
    throw new Error(error.response?.data?.message || 'Login failed')
  }
}

// 注册接口
export interface RegisterRequest {
  email: string
  password: string
  name: string
}

export interface RegisterResponse {
  accessToken: string
  user: {
    id: string
    accountNo: string
    email: string
    role: string[]
  }
}

export const register = async (data: RegisterRequest): Promise<RegisterResponse> => {
  try {
    const response = await apiClient.post<RegisterResponse>('/auth/register', data)
    return response.data
  } catch (error: any) {
    throw new Error(error.response?.data?.message || 'Registration failed')
  }
}

// 忘记密码接口
export interface ForgotPasswordRequest {
  email: string
}

export const forgotPassword = async (data: ForgotPasswordRequest): Promise<void> => {
  try {
    await apiClient.post('/auth/forgot-password', data)
  } catch (error: any) {
    throw new Error(error.response?.data?.message || 'Failed to send reset password email')
  }
}

// 重置密码接口
export interface ResetPasswordRequest {
  token: string
  password: string
}

export const resetPassword = async (data: ResetPasswordRequest): Promise<void> => {
  try {
    await apiClient.post('/auth/reset-password', data)
  } catch (error: any) {
    throw new Error(error.response?.data?.message || 'Failed to reset password')
  }
}

// 获取用户信息接口
export interface UserProfile {
  id: string
  accountNo: string
  email: string
  role: string[]
}

export const getUserProfile = async (): Promise<UserProfile> => {
  try {
    const response = await apiClient.get<UserProfile>('/auth/profile')
    return response.data
  } catch (error: any) {
    throw new Error(error.response?.data?.message || 'Failed to fetch user profile')
  }
}

// 登出接口
export const logout = async (): Promise<void> => {
  try {
    await apiClient.post('/auth/logout')
    // 清除本地存储的令牌
    localStorage.removeItem('accessToken')
  } catch (error: any) {
    throw new Error(error.response?.data?.message || 'Logout failed')
  }
}

export default {
  login,
  register,
  forgotPassword,
  resetPassword,
  getUserProfile,
  logout,
}